﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Applica.Models;
using Omu.Drawing;

namespace Applica.Controllers
{
    public class MobileVersionController : Controller
    {
        //
        // GET: /MobileVersion/
        private homewizard_test2databaseEntities db = new homewizard_test2databaseEntities();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ChangePromoCode()
        {
            return View();
        }

        public ActionResult Customize()
        {
            Session["sponsor"] = "Andy";

            SponsorInputs345xModel model = new SponsorInputs345xModel();
            String sponser = Session["sponsor"].ToString().Trim();
            if (!String.IsNullOrEmpty(sponser))
            {

                DataRepository entities = new DataRepository();
                model = entities.GetMobileVersionData(sponser);
                try
                {
                    if (!System.IO.File.Exists(Server.MapPath("~/sponsor_iphone_images/" + model.ilogo_pic)))
                    {
                        model.ilogo_pic = "Default.png";
                    }
                }
                catch { }
                var selectedCountry = "US";
                var selectedState = "";
                if (!String.IsNullOrEmpty(model.ipscountry))
                {
                    selectedCountry = model.ipscountry;
                }
                if (!String.IsNullOrEmpty(model.ipsstateprovince))
                {
                    selectedState = model.ipsstateprovince;
                }

                //var location = db.Country_State.Select(e => new { e.country_name, e.country }).Distinct().OrderByDescending(e => e.country_name);
                ////ViewBag.Country = new SelectList(location, "country", "country", selectedCountry);

                //var state = (from s in db.Country_State
                //             where s.country == selectedCountry
                //             select s);

                //ViewBag.Country = new SelectList(location, "country", "country_name", selectedCountry);

                //ViewData["optional"] = "-Select state or region-";

                //if (selectedCountry == "CAN")
                //{
                //    ViewData["optional"] = "-Select Province-";
                //}

                //if (!String.IsNullOrEmpty(selectedState))
                //{
                //    ViewBag.State = new SelectList(state, "state_province_code", "state_or_province_name", selectedState);
                //}
                //else
                //{
                //    ViewBag.State = new SelectList(state, "state_province_code", "state_or_province_name");
                //}

            }
            return View(model);
        }
        public ActionResult banner(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "Andy";
            String sponser = Session["sponsor"].ToString().Trim();
            DataRepository entities = new DataRepository();
            model = entities.GetMobileVersionData(sponser);

            return PartialView("Bannar", model);



        }
        public ActionResult Welcome(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "Andy";
            String sponser = Session["sponsor"].ToString().Trim();
            DataRepository entities = new DataRepository();
            model = entities.GetMobileVersionData(sponser);

            return PartialView("Welcome", model);
        }
        public ActionResult Admin(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "Andy";
            String sponser = Session["sponsor"].ToString().Trim();
            DataRepository entities = new DataRepository();
            model = entities.GetMobileVersionData(sponser);
            return PartialView("Admin", model);
        }
        public ActionResult AboutMe(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "Andy";
            String sponser = Session["sponsor"].ToString().Trim();
            DataRepository entities = new DataRepository();
            model = entities.GetMobileVersionData(sponser);
            return PartialView("AboutMe", model);
        }
        public ActionResult Special(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "Andy";
            String sponser = Session["sponsor"].ToString().Trim();
            DataRepository entities = new DataRepository();
            model = entities.GetMobileVersionData(sponser);
            

            return PartialView("Special", model);
        }
        public ActionResult Customlocation(SponsorInputs345xModel model)
        {
            Session["sponsor"] = "Andy";
            String sponser = Session["sponsor"].ToString().Trim();
            model = (from s in db.SponsorInputs345x
                     where s.sponsor == sponser
                     select new SponsorInputs345xModel()
                     {
                         Sponsor_ID = s.Sponsor_ID,
                         sponsor = s.sponsor,
                         icompany_name = s.icompany_name,
                         iphone_number = s.iphone_number,
                         iname_line = s.iname_line,
                         imessage_welcome = s.imessage_welcome,
                         imessage_myscreen = s.imessage_myscreen,
                         iemail_address = s.iemail_address,
                         iwebsite = s.iwebsite,
                         ipscountry = s.ips_country,
                         ipsstateprovince = s.ips_state_province,
                         ipromocode = s.ipromocode,
                         ilogo_pic = s.ilogo_pic,
                         ispec_features_msg = s.ispec_features_msg,
                         itagline = s.itagline,
                         icompany_admin_link = s.icompany_admin_link,
                         icon_phone_number = s.icon_phone_number
                         ,
                         icon_email_address = s.icon_email_address,
                         icon_web_address = s.icon_web_address,
                         ifacebook = s.ifacebook,
                         itwitter = s.itwitter
                     }).FirstOrDefault();

            return PartialView("Customlocation", model);
        }
        public JsonResult Update(SponsorInputs345xModel model)
        {

            try
            {

                var sponser = (from s in db.SponsorInputs345x
                               where s.sponsor == model.sponsor
                               select s).First();
                if (!String.IsNullOrEmpty(model.icompany_name))
                {
                    sponser.icompany_name = model.icompany_name;
                }
                if (!String.IsNullOrEmpty(model.iphone_number))
                {
                    sponser.iphone_number = model.iphone_number;
                }
                if (!String.IsNullOrEmpty(model.iname_line))
                {
                    sponser.iname_line = model.iname_line;
                }

                if (!String.IsNullOrEmpty(model.imessage_welcome))
                {
                    sponser.imessage_welcome = model.imessage_welcome;
                }
                if (!String.IsNullOrEmpty(model.imessage_myscreen))
                {
                    sponser.imessage_myscreen = model.imessage_myscreen;
                }

                if (!String.IsNullOrEmpty(model.iemail_address))
                {
                    sponser.iemail_address = model.iemail_address;
                }

                if (!String.IsNullOrEmpty(model.iwebsite))
                {
                    sponser.iwebsite = model.iwebsite;
                }
                if (!String.IsNullOrEmpty(model.ipscountry))
                {
                    sponser.ips_country = model.ipscountry;
                }
                if (!String.IsNullOrEmpty(model.ipsstateprovince))
                {
                    sponser.ips_state_province = model.ipsstateprovince;
                }
                if (!String.IsNullOrEmpty(model.ipromocode))
                {
                    sponser.ipromocode = model.ipromocode;
                }
                if (!String.IsNullOrEmpty(model.ispec_features_msg))
                {
                    sponser.ispec_features_msg = model.ispec_features_msg;
                }
                if (!String.IsNullOrEmpty(model.itagline))
                {
                    sponser.itagline = model.itagline;
                }
                if (!String.IsNullOrEmpty(model.icompany_admin_link))
                {
                    sponser.icompany_admin_link = model.icompany_admin_link;
                }



                if (!String.IsNullOrEmpty(model.icon_phone_number))
                {
                    sponser.icon_phone_number = model.icon_phone_number;
                }
                if (!String.IsNullOrEmpty(model.icon_email_address))
                {
                    sponser.icon_email_address = model.icon_email_address;
                }
                if (!String.IsNullOrEmpty(model.icon_web_address))
                {
                    sponser.icon_web_address = model.icon_web_address;
                }
                if (!String.IsNullOrEmpty(model.ifacebook))
                {
                    sponser.ifacebook = model.ifacebook;
                }
                if (!String.IsNullOrEmpty(model.itwitter))
                {
                    sponser.itwitter = model.itwitter;
                }

                if (ModelState.IsValid)
                {
                    db.SponsorInputs345x.ApplyCurrentValues(sponser);
                    db.SaveChanges();
                }
                return Json(new { success = "<span style='color:green;' >Your changes have been saved.</span>" });
            }
            catch
            {
                return Json(new { success = "<span style='color:red;' >Some error occured.</span>" });
            }

        }
        
        [HttpPost]
        public ContentResult UploadFiles(string id)
        {
            decimal Lx = 200;
            decimal Ly = 71;
            decimal L2;
            decimal newWidth = 200, newHeight = 71;
            var r = new List<UploadFilesResult>();
            SponsorInputs345xModel model = new SponsorInputs345xModel();
            model.Sponsor_ID = Convert.ToInt32(id);
            foreach (string file in Request.Files)
            {
                Int32 id_ = Convert.ToInt32(id);
                var sponser = (from s in db.SponsorInputs345x
                               where s.Sponsor_ID == id_
                               select s).First();
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                if (hpf.ContentLength == 0)
                    continue;
                Image originalImg = System.Drawing.Image.FromStream(hpf.InputStream);
                if (originalImg.Width > originalImg.Height)
                {
                    decimal ratio = Convert.ToDecimal(originalImg.Width) / Convert.ToDecimal(originalImg.Height);
                    newWidth = ratio * newHeight;



                }
                else
                {
                    decimal ratio = Convert.ToDecimal(originalImg.Height) / Convert.ToDecimal(originalImg.Width);
                    newHeight = ratio * newWidth;

                }




                string savedFileName = Path.Combine(Server.MapPath("~/Temp"), Path.GetFileName(hpf.FileName));
                //Rename Image
                string newname = "";

                string extension = Path.GetExtension(hpf.FileName);
                if (sponser.ilogo_pic.Contains("-1"))
                {
                    newname = id + "_" + "iphone_image" + extension;
                }
                else
                {
                    newname = id + "_" + "iphone_image-1" + extension;
                }
                savedFileName = Path.Combine(Server.MapPath("~/Temp"), newname);

                hpf.SaveAs(savedFileName);

                r.Add(new UploadFilesResult()
                {
                    Name = hpf.FileName,
                    Length = hpf.ContentLength,
                    Type = hpf.ContentType,
                    ImagePath = newname
                });


                sponser.ilogo_pic = newname;

                if (ModelState.IsValid)
                {
                    db.SponsorInputs345x.ApplyCurrentValues(sponser);
                    db.SaveChanges();
                    db.Dispose();
                }


                using (var image = Image.FromFile(savedFileName))
                {
                    int x = 0;
                    int y = 0;
                    if (Convert.ToInt32(newWidth) > Lx)
                    {
                        x = Convert.ToInt32(newWidth) - Convert.ToInt32(Lx);
                        x = x / 2;
                    }
                    else
                    {
                        y = Convert.ToInt32(newHeight) - Convert.ToInt32(Ly);
                        y = y / 2;
                    }
                    //var img = Imager.Crop(image, new Rectangle(0, 0, Convert.ToInt32(newWidth), Convert.ToInt32(newHeight)));
                    Image resized = Imager.Resize(image, Convert.ToInt32(newWidth), Convert.ToInt32(newHeight), true);


                    // var img = Imager.Crop(resized, new Rectangle(x, y, 125, 121));
                    Imager.SaveJpeg(Path.Combine(Server.MapPath("~/sponsor_iphone_images"), newname), resized);
                }



                // System.IO.File.Delete(savedFileName);
            } //,\"path\":\"" + r[0].ImagePath + "\"
            return Content("{\"name\":\"" + r[0].Name + "\",\"path\":\"" + r[0].ImagePath + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");

        }
        
        [HttpPost]
        public ContentResult restoreFile(SponsorInputs345xModel model)
        {
            Int32 id_ = Convert.ToInt32(model.Sponsor_ID);
            var sponser = (from s in db.SponsorInputs345x
                           where s.Sponsor_ID == id_
                           select s).First();
            sponser.ilogo_pic = "Default.jpg";
            var image = sponser.ilogo_pic;
            if (ModelState.IsValid)
            {
                db.SponsorInputs345x.ApplyCurrentValues(sponser);
                db.SaveChanges();
                db.Dispose();
            }
            return Content("{\"name\":\"" + image + "\"}", "application/json");
        }
    }
}
